#include <monitor_settings.h>
#include <kdialog.h>
#include <QPushButton>
#include <QApplication>
#include <QGroupBox>
#include <QScreen>

MonitorSettings::MonitorSettings(QWidget *parent)
    : KWidget{parent},
      settings("ukui-monitor-overlay", "settings")
{
    setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint | Qt::WindowTitleHint);
    setStyleSheet("background-color: rgba(255, 255, 255, 255); color: black;");
    setMinimumWidth(420);

    layout = new QVBoxLayout(this);

    baseBar()->setLayout(layout);

    iconBar()->setWidgetName("监视器设置");
    //iconBar()->setIcon("kylin-settings");

    //createAboutDialog();


    // 获取菜单对象
    kdk::KMenuButton* menu = windowButtonBar()->menuButton();

    // 菜单关于按钮
    QAction* aboutAction = menu->aboutAction();
    connect(aboutAction, &QAction::triggered, this, [&](){
        aboutDialogue = createAboutDialog();
        aboutDialogue->show();
    });

    // 菜单退出按钮
    QAction* exitAction = menu->quitAction();
    connect(exitAction, &QAction::triggered, this, [&](){
        QApplication::exit();
    });

    // 显示菜单按钮（默认不会显示）
    menu->show();

    createOptions();
    loadSettings();

}

MonitorSettings::~MonitorSettings()
{

}

void MonitorSettings::loadSettings()
{
    settings.beginGroup("Visibility");
    cpuCheckBox->setChecked(settings.value("CPU", true).toBool());

    cpuFreqCheckBox->setChecked(settings.value("CpuFreq").toBool());

    // 未来优化成单独的函数

    bool enabled = cpuFreqCheckBox->isChecked();
    cpuShowTypeComboBox->setEnabled(enabled);
    cpuShowUnitComboBox->setEnabled(enabled);

    if (!enabled)
    {
        cpuShowTypeComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
        cpuShowUnitComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
    }
    else
    {
        cpuShowTypeComboBox->setStyleSheet("");
        cpuShowUnitComboBox->setStyleSheet("");
    }


    cpuShowTypeComboBox->setCurrentIndex(settings.value("CpuShowType").toInt());
    cpuShowUnitComboBox->setCurrentIndex(settings.value("CpuFreqUnit", 0).toInt());

    memCheckBox->setChecked(settings.value("MEM", true).toBool());
    gpuCoreCheckBox->setChecked(settings.value("GPUCore", true).toBool());
    gpuMemCheckBox->setChecked(settings.value("GPUVRAM", true).toBool());

    fontSizeSlider->setValue(settings.value("FontSize", 15).toInt());
    fontSizeSpinBox->setValue(settings.value("FontSize", 15).toInt());

    fontColor = (settings.value("FontColor", "#ffffff")).toString();
    fontColorPreviewWidget->setStyleSheet(QString("background-color: %1; border: 1px solid gray;").arg(fontColor));



    settings.endGroup();
}

void MonitorSettings::saveSettings()
{
    settings.beginGroup("Visibility");
    settings.setValue("CPU", cpuCheckBox->isChecked());
    settings.setValue("CpuFreq", cpuFreqCheckBox->isChecked());
    settings.setValue("CpuShowType", cpuShowTypeComboBox->currentIndex());
    settings.setValue("CpuFreqUnit", cpuShowUnitComboBox->currentIndex());
    settings.setValue("MEM", memCheckBox->isChecked());
    settings.setValue("GPUCore", gpuCoreCheckBox->isChecked());
    settings.setValue("GPUVRAM", gpuMemCheckBox->isChecked());

    settings.setValue("FontSize", fontSizeSpinBox->value());
    settings.setValue("FontColor", fontColor);
    settings.endGroup();
}

bool MonitorSettings::isCpuUsageVisible() const
{
    return cpuCheckBox->isChecked();
}

bool MonitorSettings::isCpuFreqVisible() const
{
    return cpuFreqCheckBox->isChecked();
}

int MonitorSettings::getCpuFreqVisibleType() const
{
    return cpuShowTypeComboBox->currentIndex();
}

CpuMonitor::FreqUnit MonitorSettings::getCpuFreqVisibleUnit() const
{
    return (cpuShowUnitComboBox->currentIndex() == 0) ? CpuMonitor::FreqUnit::MHZ : CpuMonitor::FreqUnit::GHZ;
}

bool MonitorSettings::isMemUsageVisible() const
{
    return memCheckBox->isChecked();
}

bool MonitorSettings::isGpuCoreUsageVisible() const
{
    return gpuCoreCheckBox->isChecked();
}

bool MonitorSettings::isGpuMemUsageVisible() const
{
    return gpuMemCheckBox->isChecked();
}

int MonitorSettings::getFontSize() const
{
    return fontSizeSpinBox->value();

}

QColor MonitorSettings::getFontColor() const
{
    return fontColor;

}

void MonitorSettings::createOptions()
{

    QGroupBox *visableOptionsGroup = new QGroupBox("显示选项", this);

    cpuCheckBox = new QCheckBox("显示CPU使用率", this);
    cpuFreqCheckBox = new QCheckBox("显示CPU核心频率", this);



    QHBoxLayout *cpuShowTypeLayout = new QHBoxLayout();

    // 左间距
    cpuShowTypeLayout->addSpacerItem(new QSpacerItem(28, 1));

    QLabel *cpuShowTypeLabel = new QLabel("CPU显示模式");
    cpuShowTypeComboBox = new QComboBox(this);
    cpuShowTypeComboBox->addItem("显示全部核心频率（详细）");
    cpuShowTypeComboBox->addItem("显示平均频率（简洁）");

    cpuShowTypeLayout->addWidget(cpuShowTypeLabel, 1);
    cpuShowTypeLayout->addWidget(cpuShowTypeComboBox, 2);

    QHBoxLayout *cpuShowUnitLayout = new QHBoxLayout();

    QLabel *cpuShowUnitLabel = new QLabel("CPU频率单位");

    cpuShowUnitLayout->addSpacerItem(new QSpacerItem(28, 1));

    cpuShowUnitComboBox = new QComboBox(this);
    cpuShowUnitComboBox->addItem("MHz");
    cpuShowUnitComboBox->addItem("GHz");

    cpuShowUnitLayout->addWidget(cpuShowUnitLabel, 1);
    cpuShowUnitLayout->addWidget(cpuShowUnitComboBox, 2);


    memCheckBox = new QCheckBox("显示内存使用率", this);
    gpuCoreCheckBox = new QCheckBox("显示GPU核心使用率", this);
    gpuMemCheckBox = new QCheckBox("显示GPU内存使用率", this);

    auto notifyVisableChange = [=]() {
        saveSettings();
        emit visibilityChanged();
    };

    connect(cpuCheckBox, &QCheckBox::stateChanged, notifyVisableChange);
    connect(cpuFreqCheckBox, &QCheckBox::stateChanged, notifyVisableChange);
    connect(cpuFreqCheckBox, &QCheckBox::stateChanged, [&](){
        bool enabled = cpuFreqCheckBox->isChecked();
        cpuShowTypeComboBox->setEnabled(enabled);
        cpuShowUnitComboBox->setEnabled(enabled);

        if (!enabled)
        {
            cpuShowTypeComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
            cpuShowUnitComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
        }
        else
        {
            cpuShowTypeComboBox->setStyleSheet("");
            cpuShowUnitComboBox->setStyleSheet("");
        }
    });

    connect(cpuShowTypeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), notifyVisableChange);
    connect(cpuShowUnitComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), notifyVisableChange);
    connect(cpuShowUnitComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [this](){
        emit cpuFreqUnitChanged();
    });



    connect(memCheckBox, &QCheckBox::stateChanged, notifyVisableChange);
    connect(gpuCoreCheckBox, &QCheckBox::stateChanged,  notifyVisableChange);
    connect(gpuMemCheckBox, &QCheckBox::stateChanged, notifyVisableChange);

    // 显示控制总布局

    QVBoxLayout *visableOptions = new QVBoxLayout;
    visableOptions->addWidget(cpuCheckBox);
    visableOptions->addWidget(cpuFreqCheckBox);
    visableOptions->addLayout(cpuShowTypeLayout);
    visableOptions->addLayout(cpuShowUnitLayout);
    visableOptions->addWidget(memCheckBox);
    visableOptions->addWidget(gpuCoreCheckBox);
    visableOptions->addWidget(gpuMemCheckBox);
    visableOptionsGroup->setLayout(visableOptions);

    QGroupBox *fontSettingsGroup = new QGroupBox("字体设置", this);

    // 字体大小设置

    fontSizeLabel = new QLabel("字体大小");
    fontSizeSlider = new QSlider(this);
    fontSizeSlider->setOrientation(Qt::Horizontal);
    fontSizeSlider->setMaximum(100);
    fontSizeSlider->setMinimum(5);

    fontSizeSpinBox = new QSpinBox(this);
    fontSizeSpinBox->setRange(10, 100);
    fontSizeSpinBox->setValue(fontSizeSlider->value());

    auto notifyFontSizeChange = [=](int value) {
        fontSizeSpinBox->setValue(value);
        fontSizeSlider->setValue(value);
        saveSettings();
        emit fontSizeChanged();
    };

    connect(fontSizeSlider, &QSlider::valueChanged, notifyFontSizeChange);
    connect(fontSizeSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), notifyFontSizeChange);

    QHBoxLayout *fonthlayout = new QHBoxLayout;
    fonthlayout->addWidget(fontSizeLabel, 1);
    fonthlayout->addWidget(fontSizeSlider, 3); // 滑动条占更大空间
    fonthlayout->addWidget(fontSizeSpinBox, 1);



    // 字体颜色设置

    fontColorLabel = new QLabel("字体颜色", this);

    fontColorPreviewWidget = new QWidget(this);
    fontColorPreviewWidget->setFixedSize(50, 30); // 设置大小
    fontColorPreviewWidget->setStyleSheet("border: 1px solid gray;");

    fontColorSelectButton = new kdk::KBorderButton("选择字体颜色", this);

    //fontColor = Qt::white;

    connect(fontColorSelectButton, &QPushButton::pressed, [this]() {
        QColor selectedColor = QColorDialog::getColor(fontColor, this);
        if (selectedColor.isValid()) {
            fontColor = selectedColor.name();
            qDebug() << fontColor;
            QString styleSheet = QString("background-color: %1; border: 1px solid gray;")
                    .arg(fontColor);
            fontColorPreviewWidget->setStyleSheet(styleSheet);
            emit fontColorChanged();
            saveSettings();
        }

    });

    QHBoxLayout *fontcolorLayout = new QHBoxLayout(this);
    fontcolorLayout->addWidget(fontColorLabel, 1);
    fontcolorLayout->addWidget(fontColorPreviewWidget, 2);
    fontcolorLayout->addWidget(fontColorSelectButton, 1);

    QVBoxLayout *settingsLayout = new QVBoxLayout;
    settingsLayout->addLayout(fonthlayout);
    settingsLayout->addLayout(fontcolorLayout);

    fontSettingsGroup->setLayout(settingsLayout);



    QGroupBox *bgSettingsGroup = new QGroupBox("背景设置", this);

    // 总体布局：纵向排列
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(visableOptionsGroup);
    mainLayout->addWidget(fontSettingsGroup);
    mainLayout->addWidget(bgSettingsGroup);


    // 添加到页面布局
    layout->addLayout(mainLayout);

}

kdk::KAboutDialog* MonitorSettings::createAboutDialog()
{
    kdk::KAboutDialog* aboutDialogue = new kdk::KAboutDialog();
    //aboutDialogue->setAppPrivacyLabelVisible(true);

    aboutDialogue->setAppSupport("computerlub@163.com");
    aboutDialogue->setWindowTitle("关于");
    aboutDialogue->setAppName("Monitor Overlay");
    aboutDialogue->setAppVersion("版本：0.0.1");
    aboutDialogue->setBodyTextVisiable(true);

    // 不知道为啥不这样设置关闭关于窗口会退出程序，先强制断开所有信号连接
    disconnect(aboutDialogue->closeButton(), &QPushButton::clicked, nullptr, nullptr);
    connect(aboutDialogue->closeButton(), &QPushButton::clicked, this, [&](){
        this->aboutDialogue->hide();
    });
    return aboutDialogue;
}


